﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Runtime.Remoting.Contexts;

namespace TodoApi.Api.Data
{
    public class EntityframeworkRepository : ITodoRepository
    {

        public Models.Todo Get(int id)
        {
            using (var context = new TodosContext())
            {
                var todo = context.Todos.SingleOrDefault(t => t.TodoId == id);
                return todo;
            }
        }

        public Models.Todo Add(Models.Todo todo)
        {
            using (var context = new TodosContext())
            {
                context.Todos.Add(todo);
                context.SaveChanges();
                return todo;
            }
        }

        public void Remove(int id)
        {
            using (var context = new TodosContext())
            {
                var todo = context.Todos.SingleOrDefault(t => t.TodoId == id);
                context.Entry(todo).State = EntityState.Deleted;
                context.SaveChanges();

            }
        }

        public void Complete(int id)
        {
            throw new NotImplementedException();
        }

        public List<Models.Todo> List()
        {
            using (var context = new TodosContext())
            {
                return context.Todos.AsNoTracking().ToList();
            }
        }

        public Models.Todo Update(Models.Todo todo)
        {
            using (var context = new TodosContext())
            {
                // This works and is best if populating POCOs from entities
                //var todoToUpdate = FindEntityById(todo.TodoId.GetValueOrDefault());
                //context.Entry(todoToUpdate).CurrentValues.SetValues(todo); // apply all properties!!
                //context.SaveChanges();
                //return todo;
              
                // Conversion error
                //_Context.Todos.AddOrUpdate(todo); // apply new properties!!
                //_Context.SaveChanges();
                //return todo;
                
                // Check if detached then attach it and then modify the state!!
                var todoEntry = context.Entry(todo);

                if (todoEntry.State == EntityState.Detached)
                {
                    context.Todos.Attach(todo);
                }

                todoEntry.State = EntityState.Modified; // apply new properties!!
                context.SaveChanges();
                return todo;
            }
        }


    }
}